import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/tables/index.dart';
import 'package:flutter_hplus/theme/theme.dart';
import 'package:get/get.dart';

import 'system_user_controller.dart';
import 'system_user_model.dart';

class SystemUserListPage extends StatelessWidget {
  const SystemUserListPage({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(SystemUserController());
    final theme = HTheme.of(context);

    return Scaffold(
        body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 顶部搜索区域
          Container(
            padding: EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(4),
              boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 5, offset: const Offset(0, 2))],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 搜索条件区域
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey.shade300),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text('用户名、真实姓名、昵称、邮箱', style: TextStyle(color: Colors.grey)),
                      ),
                    ),
                    SizedBox(width: 12),
                    DropdownButton<String>(
                      value: '所有状态',
                      items: const [
                        DropdownMenuItem(value: '所有状态', child: Text('所有状态')),
                        DropdownMenuItem(value: '正常', child: Text('正常')),
                        DropdownMenuItem(value: '锁定', child: Text('锁定')),
                      ],
                      onChanged: (value) {
                        // 实现状态筛选
                      },
                    ),
                    SizedBox(width: 12),
                    ElevatedButton.icon(
                      onPressed: () => controller.fetchUsers(),
                      icon: const Icon(Icons.refresh),
                      label: const Text('刷新'),
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.amber, foregroundColor: Colors.white),
                    ),
                    SizedBox(width: 8),
                    ElevatedButton.icon(
                      onPressed: () {
                        // 搜索逻辑
                      },
                      icon: const Icon(Icons.search),
                      label: const Text('搜索'),
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.blue, foregroundColor: Colors.white),
                    ),
                  ],
                ),
              ],
            ),
          ),

          SizedBox(height: 16),

          // 操作按钮区域
          Row(
            children: [
              ElevatedButton.icon(
                onPressed: () => _showAddUserDialog(context, controller),
                icon: const Icon(Icons.add),
                label: const Text('添加'),
                style: ElevatedButton.styleFrom(backgroundColor: Colors.blue, foregroundColor: Colors.white),
              ),
              SizedBox(width: 8),
              OutlinedButton.icon(
                onPressed: () => controller.fetchUsers(),
                icon: const Icon(Icons.refresh),
                label: const Text('刷新'),
                style: OutlinedButton.styleFrom(foregroundColor: Colors.blue),
              ),
              const Spacer(),
              IconButton(
                tooltip: '列设置',
                icon: const Icon(Icons.view_column, color: Colors.grey),
                onPressed: () {
                  // 显示列设置
                },
              ),
              IconButton(
                tooltip: '导出',
                icon: const Icon(Icons.download, color: Colors.grey),
                onPressed: () {
                  // 导出数据
                },
              ),
              IconButton(
                tooltip: '打印',
                icon: const Icon(Icons.print, color: Colors.grey),
                onPressed: () {
                  // 打印数据
                },
              ),
            ],
          ),

          SizedBox(height: 16),

          // 用户列表区域
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
                boxShadow: [
                  BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 5, offset: const Offset(0, 2)),
                ],
              ),
              child: Obx(
                () =>
                    controller.isLoading.value
                        ? const Center(child: CircularProgressIndicator())
                        : _buildUserTable(controller, context),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserTable(SystemUserController controller, BuildContext context) {
    if (controller.users.isEmpty) {
      return const Center(child: Text('暂无用户数据'));
    }

    // 定义表格列
    final List<HDataColumn> columns = [
      const HDataColumn(label: 'ID', field: 'id', numeric: true),
      const HDataColumn(label: '用户名', field: 'username'),
      const HDataColumn(label: '真实姓名', field: 'truename'),
      const HDataColumn(label: '昵称', field: 'nickname'),
      const HDataColumn(label: '手机号', field: 'phone'),
      const HDataColumn(label: '邮箱', field: 'email'),
      HDataColumn(
        label: '状态',
        field: 'status',
        cellBuilder: (value, rowData, rowIndex) {
          final int status = value as int;
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            margin: EdgeInsets.symmetric(vertical: 6),
            decoration: BoxDecoration(
              color: (status == 0 ? Colors.green : Colors.red).withOpacity(0.1),
              borderRadius: BorderRadius.circular(2),
              border: Border.all(color: status == 0 ? Colors.green : Colors.red),
            ),
            child: Text(
              status == 0 ? '正常' : '锁定',
              style: TextStyle(color: status == 0 ? Colors.green : Colors.red, fontSize: 12),
              textAlign: TextAlign.center,
            ),
          );
        },
      ),
      HDataColumn(
        label: '创建时间',
        field: 'createTime',
        formatValue: (value) {
          final DateTime date = value as DateTime;
          return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
        },
      ),
      HDataColumn(
        label: '最后登录',
        field: 'loginTime',
        formatValue: (value) {
          final DateTime date = value as DateTime;
          return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
        },
      ),
      HDataColumn(
        label: '操作',
        field: 'id',
        cellBuilder: (value, rowData, rowIndex) {
          final user = controller.users.firstWhere((u) => u.id == value);
          return Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              IconButton(
                icon: const Icon(Icons.edit, color: Colors.blue, size: 20),
                onPressed: () {
                  // 编辑用户
                },
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                tooltip: '编辑',
              ),
              SizedBox(width: 8),
              IconButton(
                icon: Icon(
                  user.status == 0 ? Icons.lock : Icons.lock_open,
                  color: user.status == 0 ? Colors.orange : Colors.green,
                  size: 20,
                ),
                onPressed: () {
                  // 锁定/解锁用户
                  controller.updateUserStatus(user.id, user.status == 0 ? 1 : 0);
                },
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                tooltip: user.status == 0 ? '锁定' : '解锁',
              ),
              SizedBox(width: 8),
              IconButton(
                icon: const Icon(Icons.key, color: Colors.purple, size: 20),
                onPressed: () {
                  // 重置密码
                  controller.resetPassword(user.id);
                },
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                tooltip: '重置密码',
              ),
              SizedBox(width: 8),
              IconButton(
                icon: const Icon(Icons.delete, color: Colors.red, size: 20),
                onPressed: () {
                  // 删除用户
                  _showDeleteUserDialog(context, controller, user);
                },
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                tooltip: '删除',
              ),
            ],
          );
        },
      ),
    ];

    // 将用户数据转换为Map格式以适应HDataTable
    final List<Map<String, dynamic>> userData =
        controller.users
            .map(
              (user) => {
                'id': user.id,
                'username': user.username,
                'truename': user.truename,
                'nickname': user.nickname,
                'phone': user.phone,
                'email': user.email,
                'status': user.status,
                'createTime': user.createTime,
                'loginTime': user.loginTime,
              },
            )
            .toList();

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: HDataTable(
        columns: columns,
        data: userData,
        showBorder: true,
        showStripes: true,
        showHover: true,
        enablePagination: true,
        enableSearch: true,
        leftActions: [
          Checkbox(value: false, onChanged: (_) {}, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
          const SizedBox(width: 8),
          const Text('全选'),
        ],
        onRowTap: (row) {
          // 行点击事件，可以添加行选择逻辑
        },
      ),
    );
  }

  void _showAddUserDialog(BuildContext context, SystemUserController controller) {
    final usernameController = TextEditingController();
    final truenameController = TextEditingController();
    final nicknameController = TextEditingController();
    final phoneController = TextEditingController();
    final emailController = TextEditingController();
    final passwordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('添加用户'),
          content: SizedBox(
            width: 500,
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: usernameController,
                    decoration: const InputDecoration(
                      labelText: '用户名',
                      hintText: '请输入用户名',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: passwordController,
                    obscureText: true,
                    decoration: const InputDecoration(labelText: '密码', hintText: '请输入密码', border: OutlineInputBorder()),
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: truenameController,
                    decoration: const InputDecoration(
                      labelText: '真实姓名',
                      hintText: '请输入真实姓名',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: nicknameController,
                    decoration: const InputDecoration(labelText: '昵称', hintText: '请输入昵称', border: OutlineInputBorder()),
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                      border: OutlineInputBorder(),
                    ),
                    keyboardType: TextInputType.phone,
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: emailController,
                    decoration: const InputDecoration(labelText: '邮箱', hintText: '请输入邮箱', border: OutlineInputBorder()),
                    keyboardType: TextInputType.emailAddress,
                  ),
                ],
              ),
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            ElevatedButton(
              onPressed: () {
                if (usernameController.text.trim().isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请输入用户名')));
                  return;
                }

                if (passwordController.text.trim().isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请输入密码')));
                  return;
                }

                final newUser = SystemUserModel(
                  id: DateTime.now().millisecondsSinceEpoch, // 临时ID
                  username: usernameController.text.trim(),
                  truename: truenameController.text.trim(),
                  nickname: nicknameController.text.trim(),
                  phone: phoneController.text.trim(),
                  email: emailController.text.trim(),
                  status: 0,
                  createTime: DateTime.now(),
                  loginTime: DateTime.now(),
                );

                controller.addUser(newUser).then((success) {
                  if (success) {
                    Navigator.pop(context);
                  }
                });
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteUserDialog(BuildContext context, SystemUserController controller, SystemUserModel user) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('删除用户'),
          content: Text('确定要删除用户 "${user.username}" 吗？'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            ElevatedButton(
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              onPressed: () {
                controller.deleteUser(user.id).then((success) {
                  if (success) {
                    Navigator.pop(context);
                  }
                });
              },
              child: const Text('确定删除', style: TextStyle(color: Colors.white)),
            ),
          ],
        );
      },
    );
  }
}
